<template>
    <div>
        <div class="e-m-t-45">
            <div class="flex">
                <div class="e-flex-1">
                    <el-button type="primary" icon="el-icon-plus" plain @click="dialogVisible = true">新增员工</el-button>
                </div>
                <el-form :inline="true" class="demo-form-inline">
                    <el-form-item label="">
                        <el-input placeholder="请输入" v-model="key" prefix-icon="el-icon-search" clearable></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="注册日期" prop="">
                        <el-date-picker v-model="data" type="daterange" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="setTime" :unlink-panels="true">
                        </el-date-picker>
                    </el-form-item> -->
                    <!-- <el-form-item label="IC卡编号">
                        <el-input placeholder="请输入" prefix-icon="el-icon-search" v-model="iccode" clearable >
                        </el-input>
                    </el-form-item> -->
                    <el-form-item>
                        <el-button type="primary" @click="getList">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <!-- 更多筛选条件 -->
        <div class="other-search-form is-active" v-if="franchiseId == null">
            <el-form label-position="left" :inline="true" size="small">
                <div class="flex align-items-center">
                    <div class="e-flex-1">
                        <el-form-item label="所属加盟商">
                            <franchiseList v-model="innerFranchiseId" :firstSelect="true" @change="selectFranchise"></franchiseList>
                        </el-form-item>
                    </div>
                    <div class="e-flex-1">

                    </div>
                    <div class="e-flex-1">

                    </div>
                </div>
            </el-form>
        </div>
        <el-table :data="tableData" style="width: 100%" :border="true" @row-click="rowClick">
            <el-table-column fixed type="index" width="50">
            </el-table-column>
            <el-table-column fixed label="员工名称">
                <template slot-scope="scope">
                    <div class="user-face">
                        <div class="avatar">
                            <el-avatar v-if="scope.row.photo" :src="fileURL + scope.row.photo" :size="40"></el-avatar>
                            <el-avatar v-else :size="40">{{ scope.row.name.charAt(0) }}</el-avatar>
                        </div>
                        <div class="name e-p-l-15">{{ scope.row.name }}{{ userdetail.id == scope.row.userid?'(我)':'' }}</div>
                        <div v-if="scope.row.issuper == true">(超级管理员)</div>
                        <div v-if="scope.row.isentry == false">(已移除)</div>
                        <!-- <div class="name e-p-l-15" v-html="scope.row.name"></div> -->
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="franchisename" label="所属加盟商" width="150">
                <template slot-scope="scope">
                    <span>{{ scope.row.franchisename }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="mobile" label="手机号" width="150">
            </el-table-column>
            <!-- <el-table-column label="是否接线上单" width="150">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.isbrother"
                        @change="switchManagerState($event, scope.row)"></el-switch>
                </template>
            </el-table-column> -->
            <!-- <el-table-column label="是否为管理员" width="150">
                <template slot-scope="scope">
                    <el-switch v-if="scope.row.issuper == false" v-model="scope.row.ismanager" @change="switchManagerState($event, scope.row)"></el-switch>
                </template>
            </el-table-column> -->
            <el-table-column label="操作" fixed="right" width="300">
                <template slot-scope="scope">
                    <!-- <el-button @click="views(scope.row.id)" type="text" size="small">查看</el-button> -->
                    <!-- <el-tooltip class="item" effect="dark" content="按住ctrl键+鼠标左键新窗口打开" placement="left-start">
                        <el-button type="text" size="small" @click.stop="views($event, scope.row)">查看</el-button>
                    </el-tooltip> -->
                    <div v-if="userdetail.id != scope.row.userid">
                        <el-button type="text" @click='Remove(scope.row)' size="small" v-if="scope.row.issuper == false">
                            <span>移除</span>
                        </el-button>
                        <el-button type="text" @click='setSuper(scope.row)' size="small" v-if="scope.row.issuper == false">
                            <span>设置为超级管理员</span>
                        </el-button>
                    </div>
                    <!-- <el-button type="text" @click='pawsss(scope.row)' size="small">重置密码</el-button> -->
                </template>
            </el-table-column>
        </el-table>
        <div class="table-pagination">
            <el-pagination background layout="sizes, total, prev, pager, next" :total="total"
                :page-sizes="[10, 50, 100, 200]" :page-size="pageSize" :current-page="page" @current-change="pageChange"
                @size-change="handleSizeChange">
            </el-pagination>
        </div>

        <el-dialog title="新增用户" :visible.sync="dialogVisible" width="500px">
            <el-form ref="addForm" :model="addForm" :rules="rules" label-width="140px">
                <!-- <el-form-item label="用户名" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item> -->
                <!-- <el-form-item label="选择用户" prop="name">
                    <customerList v-model="addForm.userId" :isAll="true" @getDetails="chooseUser"></customerList>
                </el-form-item> -->

                <el-form-item label="手机号码" prop="mobile">
                    <autocompleteCustomer v-model="addForm.mobile" placeholder="请输入手机号码" @select="(obj)=>{addForm.mobile = obj.mobile}"
                        @change="(val) => { addForm.mobile = val; addForm.userId = 0;nameDisabled = false }"
                        @input="() => $refs.addForm.validateField('mobile')"
                        @blur="() => $refs.addForm.validateField('mobile')">
                    </autocompleteCustomer>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="createUser">确定</el-button>
            </span>
        </el-dialog>
        <!-- <el-dialog title="重置密码" :visible.sync="dialogVisible2" width="500px">
            <el-form ref="form" :model="pform" label-width="100px">
                <el-form-item label="姓名">
                    <el-input disabled v-model="pform.name"></el-input>
                </el-form-item>
                <el-form-item label="新密码">
                    <el-input v-model="pform.newPass"></el-input>
                </el-form-item>
                <el-form-item label="确认密码">
                    <el-input v-model="pform.confirmpass"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible2 = false">取消</el-button>
                <el-button type="primary" @click="submitP">确定</el-button>
            </span>
        </el-dialog> -->
        <!-- 详情页面弹窗 -->

        <!-- <el-drawer
              title=""
              :visible.sync="viewShow.show"
              direction="rtl"
              size="80%"
              :with-header="false"
              >
              <userView v-if="viewShow.show" :id="viewShow.id" @goBack="viewShow.show = false"></userView>
        </el-drawer> -->
    </div>
</template>

<script>
import {
	mapState
} from 'vuex';
//   import userView from './components/views.vue'
import autocompleteCustomer from "@/components/form-select-type/autocompleteCustomer.vue"
import customerList from '@/components/form-select-type/customerList.vue'
import userDepartmentList from '@/components/form-select-type/userDepartmentList.vue'
import franchiseList from '@/components/form-select-type/franchiseList.vue'
export default {
    layout: 'admin',
    components: {
        customerList,
        userDepartmentList,
        franchiseList,
        autocompleteCustomer
        //   userView
    },
    props: {
        franchiseId: {
            type: [Number, String],
            default: null
        }
    },
    head() {
        return {
            title: '员工列表'
        }
    },
    data() {
        // 手机号码校验规则
        const validateMobile = (rule, value, callback) => {
            if (!value) {
                callback(new Error('手机号码不能为空'));
            } else if (!/^1[3-9]\d{9}$/.test(value)) {
                callback(new Error('请输入有效的手机号码'));
            } else {
                callback();
            }
        };
        return {
            innerFranchiseId: null,
            viewShow: {
                id: 0,
                show: false //详情页面弹窗
            },
            iccode: '',
            data: "",
            start: "",
            end: '',
            // dialogVisible2: false,
            // pform: {
            //     name: "",
            //     id: 0,
            //     newPass: "",
            //     confirmpass: ""
            // },
            loading: true,
            key: '',
            isManager: null,
            page: 1,
            pageSize: 10,
            total: 0,
            tableData: [],
            // options: [{
            //     value: 0,
            //     label: '全部'
            // },
            // {
            //     value: 1,
            //     label: '散客'
            // }, {
            //     value: 2,
            //     label: '客户组'
            // }, {
            //     value: 3,
            //     label: '小哥'
            // }],
            // 新增用户
            dialogVisible: false,
            addForm: {
                name: "",
                mobile: ""
            },
            rules: {
                mobile: [
                    { required: true, validator: validateMobile, trigger: 'blur' },
                    { min: 11, max: 11, message: '手机号码长度必须为11位', trigger: 'blur' }
                ]
            },
            // 设置加盟商员工属性
            setDialogVisible: false,
            set: {
                staffId: 0,
                franchiseId: 0,
                isManager: true,
                sBrother: true,
                quota: 0
            },
        }
    },
    computed: {
		...mapState({
			userdetail: state => state.userdetail
		})
    },
    watch: {
        dialogVisible(val) {
            if (!val) {
                this.addForm = { 
                    name: "",
                    mobile: "",
                }
            }
        },
        // dialogVisible2(val) {
        //     let that = this
        //     if (!val) {
        //         this.pform = {
        //             name: "",
        //             id: 0,
        //             newPass: "",
        //             confirmpass: ""
        //         }
        //     }
        // }
    },
    mounted() {
        if (this.franchiseId) {
            this.innerFranchiseId = this.franchiseId
        }
        this.getList()
    },
    methods: {
        // 设置超级管理员
        setSuper(row){
            this.$confirm('确认把该员工设为超级管理员吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get('/Franchise/Staff/SetSuper', { 
                    params:{
                        userId: row.userid,
                        franchiseId: row.franchiseid
                    }
                }).then(res => {
                    console.log(res)
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    this.getList()
                })
            })
        },
        chooseUser(obj){
            console.log('chooseUser',obj)
            this.addForm.mobile = obj.mobile
            // this.addForm.userId = obj.userid
        },
        selectFranchise(val){
            this.innerFranchiseId = val
            this.getList()
        },
        createUser() { //新增用户
            // let params = {
            //     ...this.addForm
            // }
            let params = {
                mobile: this.addForm.mobile
            }
            if(this.addForm.userId > 0){
                params.userId = this.addForm.userId
            }else{
                // params.name = this.addForm.name
                params.name = '手机尾号'+ this.addForm.mobile.slice(-4)
            }
            if(this.franchiseId > 0){
                params.franchiseId = this.franchiseId
            }
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    this.$axios.post('/Franchise/Staff/Add', params).then((res) => {
                        this.$message.success("新增用户成功");
                        this.dialogVisible = false
                        this.getList()
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        setTime(e) {
            console.log(e)
            if (e == null) {
                this.start = ''
                this.end = ''
                this.getList()
            } else {
                this.start = e[0]
                this.end = e[1]
            }
        },
        //设置员工运营商状态
        // switchManagerState(event, row) {
        //     this.$axios.post(`/Franchise/Staff/Set`, {
        //         staffId: row.id,
        //         isManager: row.ismanager,
        //         isBrother: row.isbrother,
        //         franchiseId: row.franchiseid
        //     }).then((res) => {
        //         this.$message.success(res.msg);
        //     }).catch((err) => {
        //         this.getList()
        //     })
        // },
        //设置员工加盟商状态
        // switchFranchiseStaff(event, row) {
        //     this.$axios.post(`/Franchise/Staff/Set`, {
        //         staffId: row.id,
        //         isManager: row.,
        //         departmentId: row.department?.id || null
        //     }).then((res) => {
        //         this.$message.success(res.msg);
        //     }).catch((err) => {
        //         this.getList()
        //     })
        // },
        getList() {
            this.tableData = []
            this.loading = true

            this.$axios.post('/Franchise/Staff/List', {
                "PageIndex": this.page,
                "PageSize": this.pageSize,
                "Key": this.key,
                "isManager": this.isManager,
                "franchiseId": this.innerFranchiseId || 0
            }).then((res) => {
                this.loading = false
                this.tableData = res.rows;
                this.total = res.total;
            }).catch((err) => {
                this.loading = false
            })
        },
        getRowStyle({ row, rowIndex }) {
            if (!row.isentry) {
                return { backgroundColor: '#f5f7fa', color: '#999' }; // 灰色背景 + 灰色文字
            }
            return {};
        },
        views(event, row) {
            if (event.ctrlKey) {
                console.log('Ctrl + 左键点击');
                // 这里可以执行你需要的操作
                let param = []
                for (let k in this.param) {
                    if (this.param[k]) {
                        param.push(`${k}=${this.param[k]}`)
                    }
                }
                this.$router.push(`/user/list?${param.join('&')}`)

                var newWindow = window.open('/user/views?id=' + row.id, '_blank');
                newWindow.focus();
            } else {
                console.log('普通点击');
                this.viewShow.id = row.id
                this.viewShow.show = true
            }
        },
        rowClick(row) {
            this.viewShow.id = row.id
            this.viewShow.show = true
        },
        pageChange(e) { // 页码切换事件
            this.page = e;
            this.getList()
        },
        handleSizeChange(val) {
            this.page = 1;
            this.pageSize = val;
            this.getList()
        },
        // 移除
        Remove(row) {
            this.$confirm('确认把该员工移除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get('/Franchise/Staff/Remove', { 
                    params:{
                        userId: row.userid,
                        franchiseId: row.franchiseid
                    }
                }).then(res => {
                    console.log(res)
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    this.getList()
                })
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.nav-bar {
    padding: 20px 0 0;
}

.send {
    margin-top: 15px;
    margin-right: 10px;
}

.dialogForm {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
        width: 50%;
        float: left;

        &.all {
            width: 100%;
        }

        .el-select {
            width: 100%;
        }
    }
}

.user-face {
    display: flex;
    align-items: center;
    position: relative;

    .male,
    .female {
        font-size: 14px;
        position: absolute;
        left: 30px;
        top: 0;
        background-color: #fff;
        height: 16px;
        width: 16px;
        line-height: 16px;
        border-radius: 6px;
    }

    .male {
        color: var(--blue);
    }

    .female {
        color: var(--pink);
    }
}
</style>